#!/usr/bin/python
# -*- coding: utf-8 -*-
# File pipe_communication.py

import os
import sys
import server_log
import const

class PipeCommunication:
    """Provide pipe communicationi encapsulation

    Give the input pipe name for read;
    Give the output pipe name for write;
    No need to create pipes, it will take care of them
    """

    def __init__( self, input, output ):
        logger = server_log.ServerLog( 'CreatePipe' ).logger
        os.umask( 0 )
        if not os.path.exists( input ):
            try:
                os.mkfifo( input )
            except IOError:
                logger.critical( "Can't create pipe %s" % input )
                sys.exit( -1 )

        if not os.path.exists( output ):
            try:
                os.mkfifo( output )
            except IOError:
                logger.critical( "Can't create pipe %s" % output )
                sys.exit( -1 )

        try:
            self.input = os.open( input, os.O_RDONLY | os.O_NONBLOCK )
        except IOError:
            logger.critical( "Can't open pipe %s" % input )
            sys.exti( -1 )

        try:
            self.output = os.open( output, os.O_RDWR | os.O_NONBLOCK )
        except IOError:
            logger.critical( "Can't open pipe %s" % output )
            os.close( input )
            exit( -1 )

        self.input_pipe_name = input
        self.output_pipe_name = output
        self.logger = logger

    def close( self ):
        os.close( self.input )
        os.close( self.output )

    def read( self ):
        """For each read return any characters in input pipe"""
        buffer = []
        string = ''
        while True:
            try:
                string = os.read( self.input, const.PIPE_READ_NUMBER )
            except OSError:
                break

            if len( string ):
                buffer.append( string )
            else:
                break

        return "".join( buffer )

    def write( self, message ):
        """Write message into output pipe
        
        Return number success write
        """
        return os.write( self.output, message )

def main():
    pipe = PipeCommunication( const.PIPE_INPUT, const.PIPE_OUTPUT )
    print 'create pipe'
    import time
    while True:
        string = pipe.read() 
        if len( string ):
            print string

        time.sleep( 0.02 )


if __name__ == '__main__':
    main()

# End of pipe_communication.py
